// 在真实环境中，如果使用firebase这种第三方auth服务的话，本文件不需要开发者开发

import { apiUrl } from './utils/const';
import { User } from './screen/project-list/search-panel';
import axios from 'axios';

const localStorageKey = '__auth_provider_token__';

export const getToken = () => window.localStorage.getItem(localStorageKey);

export const handleUserResponse = ({ user }: { user: User }) => {
    window.localStorage.setItem(localStorageKey, user.token || '');
    axios.defaults.headers.common['b-json-web-token'] = user.token || '';
    return user;
};

export const login = (data: { username: string; password: string }) => {
    return axios
        .post(`${apiUrl}/api/user/login`, { ...data })
        .then((res) => {
            const user = {
                id: res.data.data.userId,
                username: res.data.data.username,
                token: res.data.data.token,
            };
            return handleUserResponse({ user });
        })
        .catch((err) => {
            return err;
        });
};

export const register = (data: { username: string; password: string }) => {
    return axios
        .post(`${''}/api/user/register`, { ...data })
        .then((res) => {
            const user = {
                id: res.data.data.userId,
                username: res.data.data.username,
                token: res.data.data.token,
            };
            return handleUserResponse({ user });
        })
        .catch((err) => {
            const user = {
                id: 'sjidjiejijri',
                username: data.username,
                token: 'sjidjiowjsieji',
            };
            return handleUserResponse({ user });
        });
};

export const logout = async () => {
    axios.defaults.headers.common['b-json-web-token'] = '';
    window.localStorage.removeItem(localStorageKey);
};
